import java.io.*;
import java.net.*;
import java.util.*;


public class HandShaker extends Thread
{
	Socket sock;
	String username, IP;
	ChatPanel chat;
	boolean connect;
	
	public HandShaker(String ip, String user)
	{
		username = user;
		connect = true; 
		
		try {
			sock = new Socket(ip,8888);
		} catch (UnknownHostException e) {
			System.out.println("Unknown host: " + ip);
			connect = false;
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println(ip + " is not online.");
			connect = false; 
		}
	}
	
	public HandShaker(String ip, String user, ChatPanel panel)
	{
		chat = panel;
		username = user;
		connect = true;
		IP = ip.replace("/", "");
		connect = true; 
		
		try {
			sock = new Socket(IP,8888);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run()
	{
		if(connect) { 
			try
			{
				PrintWriter pw = new PrintWriter(sock.getOutputStream(), true);
				if(chat == null)
				{
					pw.println(0);
					pw.println(username);
					pw.flush();
					pw.close();
					sock.close();
				}
				else
				{
					pw.println(6);
			    	pw.println((chat.getUserList().length+1));
			    	for(String ip : chat.getUserList())
			    	{
			    		System.out.println(ip);
			    		pw.println(ip);
			    	}
		    		pw.println(chat.username + ":" + sock.getLocalAddress());
			    	pw.flush();
			    	pw.close();
					
					for(String ip : chat.getUserList()) { 
			    		System.out.println(ip);
						Talker talker = new Talker(1, username, IP.split(":")[0], ip);
		                talker.start();
					}
					chat.addIP(IP, username);
				}
			}
			catch(IOException e) { }
		}
	}
}
